package cn.smxy.search.listener;

import cn.smxy.doc.PlantDoc;
import cn.smxy.pojo.Plant;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class RabbitMQListener {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 更新和插入数据同一情况
     * @param plant
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "insert.queue"),
                    exchange = @Exchange("topic.ex"),
                    key = "insert.plant"
            )
    )
    public void insert(Plant plant) throws IOException {
        IndexRequest indexRequest = new IndexRequest("plant")
                .id(plant.getPlantId().toString());
        PlantDoc plantDoc = new PlantDoc(plant);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(plantDoc);

        indexRequest.source(json, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 删除数据
     * @param plantId
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "delete.queue"),
                    exchange = @Exchange("topic.ex"),
                    key = "delete.plant"
            )
    )
    public void remove(Long plantId) throws IOException {
        DeleteRequest request = new DeleteRequest("plant")
                .id(plantId.toString());
        client.delete(request,RequestOptions.DEFAULT);
    }
}
